/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ControlEscolar.enrollment;

import com.ControlEscolar.Beans.Enrollment;
import com.ControlEscolar.Beans.Group;
import com.ControlEscolar.Beans.GroupDetail;
import com.ControlEscolar.Beans.Student;

import com.ControlEscolar.Exceptions.AlreadyExistExp;
import com.ControlEscolar.Exceptions.DropStudentExp;
import com.ControlEscolar.Exceptions.EnrollmentExp;
import com.ControlEscolar.Exceptions.ExtraordinaryExp;
import com.ControlEscolar.Exceptions.FailedReenrollmentSemesterExp;
import com.ControlEscolar.Exceptions.FailedSubjectsExp;
import com.ControlEscolar.Exceptions.IncompleteDocumentsExp;
import com.ControlEscolar.Exceptions.IncorrectSubjectExp;
import com.ControlEscolar.Exceptions.NotFailedSubjectsExp;
import com.ControlEscolar.Exceptions.SemesterExp;
import com.ControlEscolar.Exceptions.ServiceExp;
import com.ControlEscolar.Exceptions.TypeEnrolmentExp;
import com.ControlEscolar.Services.EnrollmentService;
import com.ControlEscolar.Services.GroupService;
import com.ControlEscolar.Services.StudentService;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

/**
 *
 * @author Kossel
 */
public class EnrollmentAction extends MappingDispatchAction {
private final String ACTIVE="A";
StudentService studentService = new StudentService();
EnrollmentService enrollmentService= new EnrollmentService();
GroupService groupService = new GroupService();
ArrayList<Group> results=new ArrayList();
ArrayList<GroupDetail> resultsDetail = new ArrayList();

    

   public void getStudentInfoJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{

          String studentKey=request.getParameter("id");
          Student student=new Student();
         try{
          student=studentService.getStudent(studentKey);
                if(student!=null){
                 String json=studentToJSON(student);
                  response.getWriter().print(json);
                }else{
                  response.getWriter().print(formatError("Matricula no existe"));
                }
                   }catch(ServiceExp ex){
            response.getWriter().print(formatError("Hubo un error en el sistema"));
         }
          

    }

      public void getAvailableGroupJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException{
        try {
            String studentKey = request.getParameter("id");
            String json;
            int id_curriculum = Integer.parseInt(request.getParameter("idc"));
            int semester = Integer.parseInt(request.getParameter("semester"));
            int type = Integer.parseInt(request.getParameter("enrolType"));
            resultsDetail = enrollmentService.getGroupsToEnrol(studentKey, semester, id_curriculum, type);
            results = groupService.getGroupsToStudent(id_curriculum, semester, studentKey);
            json = groupListToJSON(results, resultsDetail);
            response.getWriter().print(json);
        } catch (DropStudentExp ex) {
            response.getWriter().print(formatError("El estudiante esta dado de baja"));
        } catch (EnrollmentExp ex) {
            response.getWriter().print(formatError("Hubo un error en la inscripcion"));
        } catch (FailedReenrollmentSemesterExp ex) {
             response.getWriter().print(formatError("Ya tiene derecho de inscribir, ya haz recursado 2 o mas veces el mismo semestre"));
        } catch (ServiceExp ex) {
              response.getWriter().print(formatError("Hubo un error en el sistema"));
        } catch (TypeEnrolmentExp ex) {
            response.getWriter().print(formatError("Hubo un error con el tipo de inscripcion"));
        } catch (IncompleteDocumentsExp ex) {
           response.getWriter().print(formatError("No se puede inscribir debido que no tiene documentos completos"));
        } catch (FailedSubjectsExp ex) {
            response.getWriter().print(formatError("No se pudo inscribir debido que tiene examen/es reprobado/s"));
        }  catch (SemesterExp ex) {
           response.getWriter().print(formatError("No tiene derecho de inscribir a este semestre"));
        } catch (ExtraordinaryExp ex) {
            response.getWriter().print(formatError("No tiene derecho de inscribir, ha reprobado todos los examenes extraordinarios"));
        } catch (NotFailedSubjectsExp ex) {
            response.getWriter().print(formatError("No se puede inscribir este semestre, debido que ya habia aprovado"));
        }
    }

     public void doEnrollment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException{
        try {
            System.out.println("servicio doEnrollment");
            EnrollForm enrollForm = (EnrollForm) form;
            ArrayList<Enrollment> groupToEnroll = formToEnrollments(enrollForm);
            enrollmentService.enrolStudent(groupToEnroll, enrollForm.getEnrollType());
            response.getWriter().print("success");
        } catch (IncorrectSubjectExp ex) {
            response.getWriter().print("Materias de inscripcion incorrecta");
        } catch (AlreadyExistExp ex) {
            response.getWriter().print("Ya estas inscritos en estos groupos, no se pudo hacer la inscripcion");
        } catch (ServiceExp ex) {
            response.getWriter().print("Error en el sistema, no se pudo hacer la inscripcion");
        } catch (ParseException ex) {
            response.getWriter().print("Error en la fecha del sistema, no se pudo hacer la inscripcion");
        }
    }


      private String groupListToJSON(ArrayList<Group> groupList, ArrayList<GroupDetail> groupListDetail){
        String json="{\"msg\":\"success\",";
          json=json+"\"group\":[";
          for(int index = 0; index<groupList.size(); index++){
                json=json+"{";
                json=json+"\"groupName\":\""+groupList.get(index).getGroupName()
                         +"\",\"subjectName\":\""+groupListDetail.get(index).getSubjectName()
                         +"\",\"professorName\":\""+groupListDetail.get(index).getProfessor_name()
                         +"\",\"subjectKey\":\""+groupList.get(index).getSubjectKey()
                         +"\",\"professorKey\":\""+groupList.get(index).getID_Professor()
                         +"\"";
                json=json+"},";
          }
        json=json.substring(0, json.length()-1);
          json=json+"]}";    
        return json;
      }

      private String studentToJSON(Student student){
          String json;
          json="{\"name\":\""+student.getName()
                  +"\", \"lastName1\":\""+student.getFirstLastName()
                  +"\", \"lastName2\":\""+student.getSecondLastName()
                  +"\", \"birthday\":\""+student.getBirthday()
                  +"\", \"tel\":\""+student.getPhone()
                  +"\", \"dir\":\""+student.getAddress()+"\",\"msg\":\"success\"}";
          return json;

      }

      private ArrayList<Enrollment> formToEnrollments(EnrollForm enrollform) throws ServiceExp, ParseException{
         Enrollment enrollment;
         String[] selectedGroupName=enrollform.getSelectedGroup();
        System.out.println("TAMANO " + selectedGroupName.length);
         int size=selectedGroupName.length;
        
        Group group;
        ArrayList groupList = new ArrayList();
            for(int index=0; index<size; index++){
                 group= new Group();
                 enrollment = new Enrollment();
                 group=findGroup(selectedGroupName[index]);
                 enrollment.setStudentKey(enrollform.getStudentKey());
                 enrollment.setSubjectKey(group.getSubjectKey());
                 enrollment.setState(ACTIVE);
                 enrollment.setSemester(enrollform.getSemester());
                 enrollment.setGroupName(selectedGroupName[index]);
                 enrollment.setID_Curriculum(enrollform.getID_Curriculum());
                 enrollment.setDates(getCurrentDate());
                 enrollment.setID_Professor(group.getID_Professor());
                 groupList.add(enrollment);
            }
          return groupList;
      }

      private Group findGroup(String name) throws ServiceExp{
            return groupService.getGroup(name);
      }

      private java.sql.Date getCurrentDate() throws ParseException{
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        return new java.sql.Date(dateFormat.parse(dateFormat.format(date)).getTime());

      }

      private String formatError(String str){
        return "{\"msg\":\""+str+"\"}";

      }

  }
